/**
 * 保存和恢复表格设置
 */
import {mapGetters, mapActions } from 'vuex'
import '../../assets/js/extensionFn.js'

export default {
  methods: {
    ...mapActions({
      setUserSetting: 'setUserSetting' 
    }),
    //保存表格设置
    saveSetting () {
      let name = this.tableId;
      let key = this.thisRouter
      let flag = false
      let _index = 0
      let _storageT = sessionStorage.getItem(name);
      _storageT = _storageT ? JSON.parse(_storageT) : []
      let _storage = _storageT.find((elem,index)=>{
        _index = index
        return elem.key==key
      })
      if(!_storage){ //没相关缓存
        _storage = {}
        flag = true
      }
      let list = this.saveListByIsMulti(this.theadsArr);
      _storage = {
        key: key,
        list: list
      }
      if(flag){ //没缓存过
        _storageT.push(_storage)
      }else{ //有缓存
        _storageT[_index] = _storage
      }
      sessionStorage.setItem(name,JSON.stringify(_storageT));
    },
    // 根据保存的设置恢复表格
    recoverTableSetting () {
      this.isReload = true;
      let name = this.tableId;
      let _storage = sessionStorage.getItem(name);
      _storage = _storage ? JSON.parse(_storage) : {};
      if(_storage && _storage.list) {
        let arr = this.theadsArr,
            sortBy = _storage.list,
            sortByObj = this.recoverListByIsMulti(sortBy),
            sortList = sortByObj.list,
            sortSecList = sortByObj.secList,
            resList = [],
            widthObj = _storage.wid,
            minWidthObj = _storage.minW;

        sortList = sortList.map((x, i) => {
          let _x = '' + x
          if ((_x).indexOf('!') > -1) {
            _x = _x.substr(1)
            let _idx = arr.findByKey('index', _x)
            arr[_idx].checked = false
          }
          return Number(_x)
        })
        resList = arr.sort(this.sortByListIndex(sortList))
        this.theadsArr = resList

        if(widthObj) {
          this.recoverWidth(widthObj, 'width');
        }
        if(minWidthObj) {
          this.recoverWidth(minWidthObj, 'minWidth');
        }
      }
      
      if (_storage.show) {
        delete _storage.show
        delete _storage.hide
      }
      sessionStorage.setItem(name,JSON.stringify(_storage))
      this.$nextTick(function(){
        this.isReload = false
      })
    },
    //根据是否有二级表头恢复列的顺序，返回一级表头的顺序数组，和二级表头的数据
    recoverListByIsMulti (arr) {
      let list = [],
          secList = [];
      for(let i = 0, len = arr.length; i < len; i++) {
        let _data = arr[i]
        if(Number.isInteger(_data) || typeof _data === 'string') {
          list.push(_data);
        } else {
          secList.push(_data);
          for(let n in _data) {
            list.push(Number(n));
          }
        }
      }
      return {
        list: list,
        secList: secList
      }
    },
    sortByListIndex (arr) {
      return function(a, b) {
        let Val1 = arr.indexOf(a.index);
        let Val2 = arr.indexOf(b.index);
        return Val1 - Val2;
      }
    },
    //根据是否有多级表头保存列表数据
    saveListByIsMulti (arr, isHide) {
      let result = [];
      for(let i = 0, len = arr.length; i< len; i++) {
        let _item = arr[i],
            _prop=_item.prop,
            checked = _item.checked,
            _res = {};
        if(_item.isMultiHeader) { //如果是二级表头的情况下，保存的结构为 [{key:'tickName'},{key:'!money'},{key:'!date'},{key:'abc',children:['a','b','c']},{key:'def'}] 
          let _arr = _item.children,
              _resArr = [],
              _obj = {};

          for(let j = 0, len = _arr.length; j < len; j++) {
            let _arrj = _arr[j]
            let _checked = _arrj.checked
            let _child_prop = _arrj.prop
            let _re = _checked ? _child_prop : '!' + _child_prop
            _resArr.push(_re);
          }
          
          _obj.prop = _prop
          _obj.children = _resArr
          result.push(_obj);
        } else {
          let key = checked ? _prop : '!' + _prop
          _res.prop = key
          result.push(_res);
        }
      }
      return result;
    },
    //恢复二级表头的顺序
    recoverSecondHeader (arr, targetArr) {
      let _this = this;
      for(let i = 0, len = arr.length; i < len; i++) {
        let _obj = arr[i],
            _idx = -1,
            index = -1,
            children = [],
            _subObj = {},
            _list = [];
        for(let n in _obj) {
          _idx = Number(n);
          _subObj = _obj[n];
          for(let x in _subObj) {
            index = Number(x);
            _list = _subObj[x];
          }
        }
        children = targetArr[index].children;
        list = list.map((x, i) => {
          let _x = '' + x
          if ((_x).indexOf('!') > -1) {
            _x = _x.substr(1)
            children[i].checked = false
          }
          return Number(_x)
        })
        children.sort(_this.sortByListIndex(_list))
      }
      return targetArr;
    },
    //恢复列宽
    recoverWidth (obj, widthName) {
      let showArr = this.theadsArr;
      for(let k in obj) {
        let value = obj[k],
            keyArr = k.split('-'),
            _k = k,
            _sec_i = -1,
            _idx = -1,
            _sec_idx = -1,
            Item = {};
        if(keyArr.length > 1) {
          _k = keyArr[0];
          _sec_i = keyArr[keyArr.length - 1];
        }
        _idx = showArr.findByKey('index', _k);//找到数据列表中，index = k的对象的索引
        if(_idx > -1) {
          if(_sec_i > -1) {
            _sec_idx = showArr[_idx].children.findByKey('index', _sec_i);
            if(_sec_i > -1) {
              Item = showArr[_idx].children[_sec_idx];
            }
          } else {
            Item = showArr[_idx];
          }
          if(Item) {
            Item[widthName] = Number(value);
          }
          
        }
      }
    },
    //根据保存的列的显示状态把数据分成两个数组（一个是显示状态的数组，一个是隐藏状态的数组）
    apartByDisplay (dataArr, show, hide) {
      let _showArr = [],_hideArr = [];
      for(let i = 0, len = dataArr.length; i < len; i++) {
        let thisData = dataArr[i];
        let index = thisData.index;
        if(show.indexOf(index) > -1) {
          _showArr.push(thisData);
        }
        if(hide.indexOf(index) > -1) {
          _hideArr.push(thisData);
        }
      }
      return {
        show: _showArr,
        hide: _hideArr
      }
    },
    //根据表格头的index在保存的数组的位置排序
    sortByIndex (arr) {
      return function(a, b) {
        let Val1 = arr.indexOf(a.index);
        let Val2 = arr.indexOf(b.index);
        return Val1 - Val2;
      }
    }
  }
}